//
//  HTTPRequestHelper.m
//  eBook
//
//  Created by Pham Vu Duong 16/11/2011
//  Copyright 2011 CMCSoft. All rights reserved.
//

#import "HTTPRequestHelper.h"
#import "Utilities.h"

@implementation HTTPRequestHelper
@synthesize httpRequestMethod,notificationReturn;

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (void)requestWithMethodName:(HTTPRequestMethod)methodName
                    andURL:(NSString*)URL
                andHttpMethod:(NSString *)httpMethod
                  andDelegate:(id<ASIHTTPRequestDelegate>)delegate
{
    [self setHttpRequestMethod:methodName];
    _request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:[URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    [_request setDelegate:delegate];
    [_request startAsynchronous];
}

- (void)dismissRequest
{
    // Cancels an asynchronous request
    [_request cancel];
    // Cancels an asynchronous request, clearing all delegates and blocks first
    [_request clearDelegatesAndCancel];
}

#pragma mark - LIST CATEGORIES

- (NSString*)getListCategories
{
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@", 
                            NSLocalizedString(@"Domain URL", @"Domain URL"), 
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString (@"Categories list path", @"Categories list path")];
    [self requestWithMethodName:REQUEST_CATEGORY_LIST andURL:urlString andHttpMethod:@"GET" andDelegate:self];
    
    return kRequestListCategoriesNotification;
}

- (NSString*)getListCategoriesWithTokenKey:(NSString*)tokenKey
{
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?tokenkey=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Categories list path", @"Categories list path"), 
                            tokenKey];

    [self requestWithMethodName:REQUEST_CATEGORY_LIST andURL:urlString andHttpMethod:@"GET" andDelegate:self];
    
    return kRequestListCategoriesNotification;
}

- (NSString*)getListCategoriesWithTokenKey:(NSString*)tokenKey AndCondition:(NSString*)conditionString
{
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?tokenkey=%@&condition=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Categories list path", @"Categories list path"), 
                            tokenKey,
                            conditionString];

    [self requestWithMethodName:REQUEST_CATEGORY_LIST andURL:urlString andHttpMethod:@"GET" andDelegate:self];
    
    return kRequestListCategoriesNotification;
}

- (NSString*)getListCategoriesWithTokenKey:(NSString*)tokenKey AndVersionLargerThan:(int)versionValue
{
    NSString * urlString = [NSString stringWithFormat:@"version>%d",versionValue];
    return [self getListCategoriesWithTokenKey:tokenKey AndCondition:urlString];
}

#pragma mark - LIST ITEMS

- (NSString*)getListItems
{
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?tokenkey=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Items list path", @"Items list path")];
    
    [self requestWithMethodName:REQUEST_ITEM_LIST andURL:urlString andHttpMethod:@"GET" andDelegate:self];
    
    return kRequestListItemsNotification;
}

- (NSString*)getListItemsWithTokenKey:(NSString*)tokenKey
{
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?tokenkey=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Items list path", @"Items list path"), 
                            tokenKey];
    
    [self requestWithMethodName:REQUEST_ITEM_LIST andURL:urlString andHttpMethod:@"GET" andDelegate:self];
    
    return kRequestListItemsNotification;
}

- (NSString*)getListItemsWithTokenKey:(NSString*)tokenKey AndCondition:(NSString*)conditionString
{
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?tokenkey=%@&condition=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Items list path", @"Items list path"), 
                            tokenKey,
                            conditionString];
    
    [self requestWithMethodName:REQUEST_ITEM_LIST andURL:urlString andHttpMethod:@"GET" andDelegate:self];
    
    return kRequestListItemsNotification;
}

- (NSString*)getListItemsWithTokenKey:(NSString*)tokenKey AndVersionLargerThan:(int)versionValue
{
    NSString * urlString = [NSString stringWithFormat:@"version>%d",versionValue];
    return [self getListItemsWithTokenKey:tokenKey AndCondition:urlString];
}

- (NSString*)getListItemsWithTokenKey:(NSString*)tokenKey ByType:(NSString*)type AndVersionLargerThan:(int)versionValue
{
    NSString * urlString = [NSString stringWithFormat:@"version>%d and type='%@'", versionValue, type];
    return [self getListItemsWithTokenKey:tokenKey AndCondition:urlString];
}

#pragma mark - Signing Up/In Service

- (NSString*)requestToSignUpWithUserName:(NSString*)userName AndPassword:(NSString*)password AndTokenKey:(NSString*)tokenKey
{
    NSString * encryptedPassword = [Utilities CategoryEncrypt:password];
    
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?username='%@'&password='%@'&tokenkey=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Signup path", @"Signup path"), 
                            userName, 
                            encryptedPassword, 
                            tokenKey];
    
    [self requestWithMethodName:REQUEST_SIGNUP andURL:urlString andHttpMethod:@"POST" andDelegate:self];
    
    return kRequestToSignUpNotification;
}

- (NSString*)requestToLogInWithUserName:(NSString*)userName AndPassword:(NSString*)password AndTokenKey:(NSString*)tokenKey
{
    NSString * encryptedPassword = [Utilities CategoryEncrypt:password];
    
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?username='%@'&password='%@'&tokenkey=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Login path", @"Login path"), 
                            userName, 
                            encryptedPassword, 
                            tokenKey];
    
    [self requestWithMethodName:REQUEST_LOGIN andURL:urlString andHttpMethod:@"POST" andDelegate:self];
    
    return kRequestToLogInNotification;
}

- (NSString*)requestChangePassword:(NSString*)userName AndPassword:(NSString*)password WithNewPassword:(NSString*)newPassword AndTokenKey:(NSString*)tokenKey
{
    NSString * encryptedPassword = [Utilities CategoryEncrypt:password];
    
    NSString * urlString = [NSString stringWithFormat:@"%@%@%@?username='%@'&password='%@'&newpassword='%@'&tokenkey=%@",
                            NSLocalizedString(@"Domain URL", @"Domain URL"),
                            NSLocalizedString(@"Project path", @"Project path"), 
                            NSLocalizedString(@"Login path", @"Login path"), 
                            userName, 
                            encryptedPassword, 
                            newPassword, 
                            tokenKey];
    
    [self requestWithMethodName:REQUEST_CHANGE_PASSWORD andURL:urlString andHttpMethod:@"POST" andDelegate:self];
    
    return kRequestChangePasswordNotification;
}

//- (NSString*)getListAttorneysWithTokenKey:(NSString*)tokenKey AndVersionLargerThan:(int)versionValue
//{
//    NSString * urlString = [NSString stringWithFormat:@"version>%d&type='attorney'",versionValue];
//    NSLog(@"HTTPRequestHelper - getListItemsWithTokenKey:%d", versionValue);
//    NSLog(@"HTTPRequestHelper - URL String: %@", urlString);
//    return [self getListItemsWithTokenKey:tokenKey AndCondition:urlString];
//}
//
//- (NSString*)getListPrisonersWithTokenKey:(NSString*)tokenKey AndVersionLargerThan:(int)versionValue
//{
//    NSString * urlString = [NSString stringWithFormat:@"itemVersion%%3E%d%%20And%%20itemType%%3D'prisoner'",versionValue];
//    NSLog(@"HTTPRequestHelper - getListPrisonersWithVersionLargerThan:%d", versionValue);
//    NSLog(@"HTTPRequestHelper - URL String: %@", urlString);
//    return [self getListItemsWithTokenKey:tokenKey AndCondition:urlString];
//}

#pragma mark - HTTPRequestHelper Delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{ 
    NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];

    if (self.httpRequestMethod == REQUEST_CATEGORY_LIST) 
    {
        [notificationCenter postNotificationName:kRequestListCategoriesNotification object:[request responseString] userInfo:nil];
    }
    else if(self.httpRequestMethod == REQUEST_ITEM_LIST)
    {
        [notificationCenter postNotificationName:kRequestListItemsNotification object:[request responseString] userInfo:nil];
    }
    else if (self.httpRequestMethod == REQUEST_SIGNUP)
    {
        [notificationCenter postNotificationName:kRequestToSignUpNotification object:[request responseString] userInfo:nil];
    }
    else if (self.httpRequestMethod == REQUEST_LOGIN)
    {
        [notificationCenter postNotificationName:kRequestToLogInNotification object:[request responseString] userInfo:nil];
    }
    else if (self.httpRequestMethod == REQUEST_CHANGE_PASSWORD)
    {
        [notificationCenter postNotificationName:kRequestChangePasswordNotification object:[request responseString] userInfo:nil];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Time out alert", @"Time out alert") 
                                                          message:NSLocalizedString(@"Time out message", @"Time out message")
                                                         delegate:self 
                                                cancelButtonTitle:@"Ok" 
                                                otherButtonTitles:nil];
    [myAlertView show];
    
    NSError *error = [request error];
    NSLog(@"%@",error);
    [[NSNotificationCenter defaultCenter] postNotificationName:kHTTPRequestFailedNotification object:[NSString stringWithFormat:@"%d",self.httpRequestMethod]];
}

@end
